package edu.npu.cv.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.npu.cv.constant.ResultCode;
import edu.npu.cv.dao.ArticleDAO;
import edu.npu.cv.entity.ArticleDO;
import edu.npu.cv.entity.PageDO;
import edu.npu.cv.entity.ResultDO;
import edu.npu.cv.enums.ArticleDeleteStatus;
import edu.npu.cv.service.ArticleService;
import edu.npu.cv.utils.PageQueryUtil;
import edu.npu.cv.vo.ArticleVO;
import edu.npu.cv.vo.MemberVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName ArticleServiceImpl
 * @Description TODO
 * @Author Quentin_zyj
 * @Date 2021/11/23 20:03
 */
@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleDAO articleDAO;

    @Override
    public ResultDO<PageDO> findAll(PageQueryUtil pageQueryUtil) {
        List<ArticleDO> articleDOS = articleDAO.getArticleDOs(pageQueryUtil);
        int total = articleDAO.selectCount(null).intValue();
        return new ResultDO<PageDO>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS,
            new PageDO(total, pageQueryUtil.getLimit(), pageQueryUtil.getPage(),
                articleDOS));
    }

    @Override
    public ResultDO<Void> deleteByIds(Long[] ids) {
        int result = articleDAO.deleteBatch(ids);
        if (result > 0) {
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } else {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
        }
    }

    @Override
    public int getArticleCount() {
        return articleDAO.selectCount(new QueryWrapper<ArticleDO>()
            .eq("is_deleted", ArticleDeleteStatus.UNDELETED))
            .intValue();
    }

    @Override
    public ArticleDO getArticleDOById(long id) {
        return articleDAO.getArticleDOById(id);
    }

    @Override
    public ResultDO<Void> saveArticle(ArticleVO articleVO) {
        ArticleDO articleDO = new ArticleDO();
        BeanUtils.copyProperties(articleVO, articleDO);
        articleDAO.insert(articleDO);
        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
    }

    @Override
    public ResultDO<Void> updateArticle(ArticleVO articleVO) {
        ArticleDO articleDO = new ArticleDO();
        BeanUtils.copyProperties(articleVO, articleDO);
        articleDO.setId(articleVO.getArticleId());
        articleDAO.updateById(articleDO);
        return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
    }
}
